<template>
  <div class="space-y-6">
    <el-card class="shadow-sm">
      <template #header>
        <div class="flex items-center justify-between">
          <div class="flex items-center space-x-4">
            <span class="text-xl font-semibold text-gray-800">图片管理</span>
            <div class="view-toggle">
              <el-button
                :type="viewMode === 'table' ? 'primary' : 'default'"
                @click="switchView('table')"
                size="small"
              >
                <el-icon>
                  <List />
                </el-icon>
              </el-button>
              <el-button
                :type="viewMode === 'waterfall' ? 'primary' : 'default'"
                @click="switchView('waterfall')"
                size="small"
              >
                <el-icon>
                  <Grid />
                </el-icon>
              </el-button>
            </div>
          </div>
          <div>
            <el-button type="primary" @click="handleAdd" class="px-4 py-2">
              <el-icon class="mr-1">
                <Plus />
              </el-icon>上传图片
            </el-button>
            <el-button
              type="danger"
              @click="handleBatchDelete"
              class="px-4 py-2"
              :disabled="selectedRows.length === 0"
            >
              <el-icon class="mr-1">
                <Delete />
              </el-icon>批量删除
            </el-button>
            <el-button
              type="primary"
              @click="handleBatchUpdate"
              class="px-4 py-2"
              :disabled="selectedRows.length === 0"
            >
              <el-icon class="mr-1">
                <Edit />
              </el-icon>批量修改
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :model="searchForm" inline>
        <el-form-item label="文件名">
          <el-input v-model="searchForm.fileName" placeholder="请输入文件名" class="w-48" />
        </el-form-item>
        <el-form-item label="分类">
          <DictSelect
            :model-value="searchForm.category"
            @update:model-value="(val) => searchForm.category = val"
            dict-type="image_category"
            placeholder="请选择分类"
            width="192px"
          />
        </el-form-item>
        <el-form-item label="标签">
          <DictSelect
            :model-value="searchForm.tags"
            @update:model-value="(val) => searchForm.tags = val"
            dict-type="image_tag"
            placeholder="请选择标签"
            width="192px"
            multiple
          />
        </el-form-item>
        <el-form-item label="上传时间">
          <el-date-picker
            v-model="searchForm.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :shortcuts="datePickerShortcuts"
            class="w-80"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 图片展示区域 -->
      <div v-if="viewMode === 'table'" class="overflow-x-auto">
        <el-table
          :data="imageList"
          v-loading="loading"
          border
          style="width: 100%"
          class="text-sm"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="fileName" label="文件名" min-width="150" />
          <el-table-column prop="fileSize" label="文件大小" width="120">
            <template #default="{ row }">{{ formatFileSize(row.fileSize) }}</template>
          </el-table-column>
          <el-table-column prop="fileType" label="文件类型" width="120" />
          <el-table-column prop="category" label="分类" width="120">
            <template #default="{ row }">
              <DictDisplay dict-type="image_category" :value="row.category" />
            </template>
          </el-table-column>
          <el-table-column prop="tags" label="标签" width="150">
            <template #default="{ row }">
              <DictTag
                v-for="tag in row.tags"
                :key="tag"
                dict-type="image_tag"
                :value="tag"
                size="small"
                class="mr-1"
              />
            </template>
          </el-table-column>

          <el-table-column
            prop="uploadTime"
            label="上传时间"
            width="180"
            :formatter="tableDateTimeFormatter"
          />
          <el-table-column prop="uploadedBy" label="上传人" />
          <el-table-column label="操作" width="180" fixed="right">
            <template #default="{ row }">
              <div class="flex space-x-2">
                <el-button type="primary" size="small" @click="handleEdit(row)" class="px-3 py-1">
                  <el-icon class="mr-1">
                    <Edit />
                  </el-icon>编辑
                </el-button>
                <el-dropdown @command="handleCommand($event, row)">
                  <el-button size="small" class="px-3 py-1">
                    <el-icon>
                      <More />
                    </el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="preview">预览</el-dropdown-item>
                      <el-dropdown-item command="copyUrl">复制URL</el-dropdown-item>
                      <el-dropdown-item command="delete" divided class="text-red-600">删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 图片瀑布流 -->
      <div v-else-if="viewMode === 'waterfall'" class="image-waterfall-container">
        <ImageWaterfall
          :images="imageList"
          @edit="handleEdit"
          @copyUrl="handleCopyUrl"
          @delete="handleDelete"
          @preview="handlePreview"
        />
      </div>

      <!-- 分页 -->
      <div class="mt-6 flex justify-end">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          class="text-sm"
        />
      </div>
    </el-card>

    <!-- 图片表单对话框 -->
    <ImageFormDialog v-model="dialogVisible" :image-data="currentImage" @success="handleSuccess" />
    
    <!-- 批量修改图片信息对话框 -->
    <BatchUpdateImageDialog v-model="batchUpdateDialogVisible" @success="handleBatchUpdateSuccess" />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getImageList, batchDeleteImages, batchUpdateImageInfo } from "@/api/image";
import ImageFormDialog from "@/components/ImageFormDialog.vue";
import BatchUpdateImageDialog from "@/components/BatchUpdateImageDialog.vue";
import DictSelect from "@/components/DictSelect.vue";
import DictDisplay from "@/components/DictDisplay.vue";
import DictTag from "@/components/DictTag.vue";
import ImageWaterfall from "@/components/ImageWaterfall.vue";
import { tableDateTimeFormatter } from "@/utils/format";

import { Plus, Edit, More, List, Grid, Delete } from "@element-plus/icons-vue";

const loading = ref(false);
const imageList = ref([]);
const dialogVisible = ref(false);
const batchUpdateDialogVisible = ref(false);
const currentImage = ref(null);
const viewMode = ref("table"); // 'table' or 'waterfall'
const selectedRows = ref([]); // 存储选中的行

const searchForm = reactive({
  fileName: "",
  category: "",
  tags: [],
  timeRange: [],
});

// 日期选择器快捷选项
const datePickerShortcuts = [
  {
    text: "最近一周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: "最近一个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    },
  },
  {
    text: "最近三个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    },
  },
];

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
});

// 格式化文件大小
const formatFileSize = (size) => {
  if (size < 1024) {
    return size + " B";
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(2) + " KB";
  } else if (size < 1024 * 1024 * 1024) {
    return (size / (1024 * 1024)).toFixed(2) + " MB";
  } else {
    return (size / (1024 * 1024 * 1024)).toFixed(2) + " GB";
  }
};

const loadImages = async () => {
  loading.value = true;
  try {
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
      fileName: searchForm.fileName,
      category: searchForm.category,
      tags: searchForm.tags.length > 0 ? JSON.stringify(searchForm.tags) : "",
    };

    // 添加时间筛选参数
    if (searchForm.timeRange && searchForm.timeRange.length === 2) {
      params.startTime = searchForm.timeRange[0];
      params.endTime = searchForm.timeRange[1];
    }

    const res = await getImageList(params);
    imageList.value = res.list || [];
    pagination.total = res.total || 0;
  } catch (error) {
    ElMessage.error("获取图片列表失败");
  } finally {
    loading.value = false;
  }
};

// 空函数，保持接口一致性
const loadCategoriesAndTags = async () => {};

const handleSearch = () => {
  pagination.current = 1;
  loadImages();
};

const handleReset = () => {
  searchForm.fileName = "";
  searchForm.category = "";
  searchForm.tags = [];
  searchForm.timeRange = [];
  pagination.current = 1;
  loadImages();
};

const handleAdd = () => {
  currentImage.value = null;
  dialogVisible.value = true;
};

const handleEdit = (row) => {
  currentImage.value = { ...row };
  dialogVisible.value = true;
};

const handleCommand = async (command, row) => {
  const imageUrl = row.url;

  switch (command) {
    case "preview":
      window.open(imageUrl, "_blank");
      break;

    case "copyUrl":
      copyToClipboard(imageUrl);
      break;

    case "delete":
      await handleDelete(row);
      break;
  }
};

// 处理瀑布流中的复制URL操作
const handleCopyUrl = (row) => {
  const imageUrl = row.url;
  copyToClipboard(imageUrl);
};

// 处理瀑布流中的预览操作
const handlePreview = (row) => {
  const imageUrl = row.url;
  window.open(imageUrl, "_blank");
};

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm("确定要删除该图片吗？", "提示");
    await batchDeleteImages({ ids: [row.id] });
    ElMessage.success("删除成功");
    loadImages();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

const handleSizeChange = (val) => {
  pagination.pageSize = val;
  loadImages();
};

const handleCurrentChange = (val) => {
  pagination.current = val;
  loadImages();
};

const handleSuccess = () => {
  dialogVisible.value = false;
  loadImages();
};

// 处理表格选择事件
const handleSelectionChange = (selection) => {
  selectedRows.value = selection;
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请至少选择一条记录");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 张图片吗？`,
      "批量删除提示"
    );

    const ids = selectedRows.value.map((row) => row.id);
    await batchDeleteImages({ ids });
    ElMessage.success("批量删除成功");
    loadImages();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("批量删除失败");
    }
  }
};

// 批量修改
const handleBatchUpdate = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请至少选择一条记录");
    return;
  }

  // 打开批量修改对话框
  batchUpdateDialogVisible.value = true;
};

// 处理批量修改成功事件
const handleBatchUpdateSuccess = async (data) => {
  try {
    const ids = selectedRows.value.map((row) => row.id);
    console.log('Calling batchUpdateImageInfo with data:', { ids, ...data });
    await batchUpdateImageInfo({ ids, ...data });
    ElMessage.success("批量修改成功");
    loadImages();
  } catch (error) {
    console.error('Batch update error:', error);
    ElMessage.error("批量修改失败");
  }
};

// 切换视图模式
const switchView = (mode) => {
  viewMode.value = mode;
};

// 复制文本到剪贴板
const copyToClipboard = (text) => {
  if (navigator.clipboard) {
    navigator.clipboard
      .writeText(text)
      .then(() => {
        ElMessage.success("URL已复制到剪贴板");
      })
      .catch(() => {
        ElMessage.error("复制失败");
      });
  } else {
    // 兼容性处理
    const textarea = document.createElement("textarea");
    textarea.value = text;
    document.body.appendChild(textarea);
    textarea.select();
    try {
      document.execCommand("copy");
      ElMessage.success("URL已复制到剪贴板");
    } catch (error) {
      ElMessage.error("复制失败");
    } finally {
      document.body.removeChild(textarea);
    }
  }
};

onMounted(() => {
  loadImages();
  loadCategoriesAndTags();
});
</script>

<style scoped>
/* 使用Tailwind CSS替代原有样式 */
</style>